package com.example.micro.netty.server.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class MyWebSocketServer {

    public static void main(String[] args) throws InterruptedException {
        //创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workderGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workderGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            //因为基于Http协议，使用Http的编解码器
                            channelPipeline.addLast(new HttpServerCodec());
                            //是以块方式写，添加chunkedWriteHandler处理器
                            channelPipeline.addLast(new ChunkedWriteHandler());

                            /**
                             * 说明
                             * 1.http数据在传输过程中是分段的，HttpObjectAggregator 就是可以将多个段聚合
                             * 2.这就是为什么，当浏览器发送大量数据时，就会发出多次http请求？需要将数据聚合
                             */
                            channelPipeline.addLast(new HttpObjectAggregator(8192));

                            /**
                             * 说明
                             * 1.对于websocket，它的数据是以 桢（frame）的形式传递
                             * 2.可以看到websocketFrame下面又六个子类
                             * 3.浏览器请求时，ws://localhost:7000/xxx 表示请求的uri
                             * 4.WebSocketServerProtocolHandler 将http协议升级为ws协议，保持长连接
                             */
                            channelPipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                            channelPipeline.addLast(new MyWebSocketServerHandler());
                        }
                    });
            System.out.println("netty 服务器启动");

            //todo  为什么是sync呢？
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();

            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workderGroup.shutdownGracefully();
        }
    }

}
